<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="staffName">
        <el-input
          v-model="queryParams.staffName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工状态" prop="staffDel">
        <el-select v-model="queryParams.staffDel" placeholder="请选择员工状态" clearable style="width: 200px;">
          <el-option
            v-for="dict in staff"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:staff:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:staff:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:staff:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:staff:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="staffList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="staffId" />
      <el-table-column label="员工姓名" align="center" prop="staffName" />
      <el-table-column label="联系电话" align="center" prop="staffTel" />
      <el-table-column label="员工住址" align="center" prop="staffAddress" />
      <el-table-column label="属性" align="center" prop="propertyNames" />
      <el-table-column label="工作档期" align="center" prop="timeNames"/>
      <el-table-column label="累计服务次数" align="center" prop="staffNum" />
      <el-table-column label="员工状态" align="center" prop="staffDel" >
        <template #default="scope">
          <div style="cursor: pointer;" @click.stop="updateDel(scope.row)">
            <dict-tag :options="staff" :value="scope.row.staffDel" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:staff:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:staff:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="staffRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工姓名" prop="staffName">
          <el-input v-model="form.staffName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="staffTel">
          <el-input v-model="form.staffTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="员工住址" prop="staffAddress">
          <el-input v-model="form.staffAddress" placeholder="请输入员工住址" />
        </el-form-item>

        <el-form-item label="属性" prop="propertyNames">
          <el-input v-model="form.propertyNames" placeholder="请选择员工属性" style="margin-bottom: 20px;" readonly />
          <el-button
          v-for="(button, index) in buttons"
          :key="index"
          :type="button.active? 'primary' : ''"
          text bg @click="buttonClick(button)"
          >{{ button.text }}</el-button>
        </el-form-item>
        <el-form-item label="时间档期" prop="timeNames">
          <el-input v-model="form.timeNames" placeholder="请选择时间档期" style="margin-bottom: 20px;" readonly />
          <el-button
          style="margin-bottom: 20px; "
          v-for="(time, index) in times"
          :key="index"
          :disabled="(index === 0 && time.active === true) || (index!== 0 && times.active===false)"
          :type="time.active? 'primary' : ''"
          text bg @click="timeClick(time)"
          >{{ time.text }}</el-button>
        </el-form-item>

        <el-form-item label="员工状态" prop="staffDel">
          <el-select v-model="form.staffDel" placeholder="请选择员工状态">
            <el-option
              v-for="dict in staff"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Staff">
import { listStaff, getStaff, delStaff, addStaff, updateStaff,addProperty, addTime, delProperty, delTime,listProperty,listTime} from "@/api/system/staff";


const { proxy } = getCurrentInstance();
const { staff } = proxy.useDict('staff');

const staffList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// const buttons=[
//   {type:'',text:'日常保洁',active:false},
//   {type:'',text:'家电清洁',active:false},
//   {type:'',text:'大扫除',active:false},
//   {type:'',text:'家电维修',active:false}
// ];

const buttons=[];
const times=[];

// const times=[
//   {type:'',text:'全天',active:false},
//   {type:'',text:'上午8:00-10:00',active:false},
//   {type:'',text:'上午10:30-12:30',active:false},
//   {type:'',text:'下午2:00-4:00',active:false},
//   {type:'',text:'下午4:30-6:30',active:false}
// ]
//点击属性按钮
const buttonClick = (button) => {
  button.active =!button.active; // 切换按钮的激活（选中）状态
  // console.log(button);
  const selectedTexts = buttons.filter(b => b.active).map(b => b.text); // 获取所有选中按钮的文本
  // console.log(selectedTexts);
  const selectedIndexs = buttons.filter(b => b.active).map(b => buttons.indexOf(b)+1); // 获取所有选中按钮的索引值
  // console.log(selectedIndexs);
  
  form.value.propertyNames = selectedTexts.join('、 '); // 将选中按钮文本用逗号拼接后显示到输入框
  form.value.propIds= selectedIndexs;
};

//点击时间按钮
const timeClick = (time) => {
  const currentIndex = times.indexOf(time);
  if (currentIndex === 0) {
    // 点击了第一个按钮，将除第一个按钮外的其他按钮设为不可用（active设为false）
    times.forEach((t, index) => {
      if (index!== 0) {
        t.active = false;
      }
    });
  } else {
    // 点击了其他按钮，将第一个按钮设为不可用
    times[0].active = false;
  }
  time.active =!time.active;
  const selectedTexts = times.filter(b => b.active).map(b => b.text);
  const selectedIndexs = times.filter(b => b.active).map(b => times.indexOf(b)+1);
  // console.log(selectedIndexs);
  // console.log(selectedTexts);
  form.value.timeIds = selectedIndexs;
  
  form.value.timeNames = selectedTexts.join(' ');
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    staffName: null,
    staffTel: null,
    staffAddress: null,
    staffNum: null,
    staffDel: null
  },
  rules: {
    staffName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    staffTel: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    staffAddress: [
      { required: true, message: "员工住址不能为空", trigger: "blur" }
    ],
    propertyNames: [
      { required: true, message: "员工属性不能为空", trigger: "blur" }
    ],
    timeNames: [
      { required: true, message: "时间档期不能为空", trigger: "blur" }
    ],
    staffDel: [
      { required: true, message: "员工状态", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工管理列表 */
function getList() {
  loading.value = true;
  listStaff(queryParams.value).then(response => {
    // console.log(response);
    staffList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//员工属性和档期
function listPropertyAndTime(){
  listProperty().then(response => {
    console.log(response.data);
    response.data.forEach((item) => {
      const button={
        type:'',
        text:item.propertyName,
        active:false
      };
      buttons.push(button);
    });
  });

  listTime().then(response => {
    console.log(response.data);
    response.data.forEach((item) => {
      const time={
        type:'',
        text:item.timeName,
        active:false
      };
      times.push(time);
    });
  });
}

//更改状态
function updateDel(row) {
  if (row.staffDel == 0) {
    row.staffDel = 1;
  } else if (row.staffDel == 1) {
    row.staffDel = 0;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    staffId: null,
    staffName: null,
    staffTel: null,
    staffAddress: null,
    propertyNames: null,
    staffDel: null,
    propIds: null,
    timeIds: null
  };
  proxy.resetForm("staffRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.staffId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加员工管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _staffId = row.staffId || ids.value
  getStaff(_staffId).then(response => {
    form.value = response.data;
    const text=form.value.propertyNames.split('、 ');
    console.log(text);
    buttons.filter(b => {
      if(text.includes(b.text)){
        b.active=true
      }
    });
    const text1=form.value.timeNames.split(' ');
    console.log(text1);
    times.filter(b => {
      if(text1.includes(b.text)){
        b.active=true
      }
    });
    
    open.value = true;
    title.value = "修改员工管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["staffRef"].validate(valid => {
    if (valid) {
      if (form.value.staffId != null) {
        updateStaff(form.value).then(response => {
          console.log(form.value);
          if(form.value.propertyNames!=staffList.value[form.value.staffId].propertyNames){
            delProperty(form.value.staffId);
            addProperty(form.value.propIds,form.value.staffId);
          }
          if(form.value.timeNames!=staffList.value[form.value.staffId].timeNames){
            delTime(form.value.staffId);
            addTime(form.value.timeIds,form.value.staffId);
          }
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStaff(form.value).then(response => {
          const id=response.data;
          const propIds=form.value.propIds;
          const timeIds=form.value.timeIds;

          addProperty(propIds,id).then(res=>{
            console.log(res);
          });
          addTime(timeIds,id);

          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _staffIds = row.staffId || ids.value;
  proxy.$modal.confirm('是否确认删除员工管理编号为"' + _staffIds + '"的数据项？').then(function() {
    return delStaff(_staffIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/staff/export', {
    ...queryParams.value
  }, `staff_${new Date().getTime()}.xlsx`)
}

getList();
listPropertyAndTime();
</script>
